package com.example.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

public class JWTUtil {
    private static  final String sign="1qaz!QAZ2wsx@WSX";
    public static String getToken(Map<String,String> params){
        //默认七天有效期
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        //创建JWTbuild
        JWTCreator.Builder builder = JWT.create();
        params.forEach((k,v)->{
            builder.withClaim(k,v);

        });
        builder.withSubject(params.get("account"));
        //指定令牌过期时间
        return builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(JWTUtil.sign));
    }
    /*
     * 验证token合法性
     * */
    public static void verity(String token){
        JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
    }
    /*
     * 获取token信息
     * */
    public static DecodedJWT getTokenInfo(String token){
        return JWT.require(Algorithm.HMAC256(sign)).build().verify(token);
    }
}
